﻿using System;
namespace ILMergeTest
{
    using System.Windows;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Reactive;
    using WP7Contrib.Caching;
    using WP7Contrib.Communications;
    using WP7Contrib.Logging;
    using WP7Contrib.Services.BingMaps;
    using WP7Contrib.Services.BingMaps.Model;
    using WP7Contrib.Services.Location;

    public partial class MainPage : PhoneApplicationPage
    {
        private IDisposable currentLocationObserver;
        private readonly ILocationService locationService;
        private readonly IBingMapsService bingMapService;

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            this.locationService = new LocationService();

            var propertyEncoder = new UrlEncoder();
            var resourceHandlerFactory = new ResourceClientFactory();
            var cacheProvider = new InMemoryCacheProvider();
            var settings = new Settings("AoAYqsmU8fmEynSb1ehNUnBPFLkTAIgDPrkk0ZymU8i_ZI-ZK6UE80zYgCyPiDwo", "EF79EAD2898E05B37E805F8547919DCA67154CBE");

            this.bingMapService = new BingMapsService(resourceHandlerFactory, propertyEncoder, cacheProvider, settings, new DebugLog());
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
        }

        private void Go_Click(object sender, RoutedEventArgs e)
        {
            this.currentLocationObserver =
                  this.locationService.Location()
                      .ObserveOnDispatcher()
                      .Subscribe(geoCoordinate =>
                      {
                          var criterion = CriterionFactory.CreateLocationSearchForPoint(geoCoordinate);
                          this.SearchForLocation(criterion);
                      });
        }

        private void SearchForLocation(ILocationSearchPointCriterion criterion)
        {
            this.bingMapService.SearchForLocationUsingPoint(criterion)
                .ObserveOnDispatcher()
                .Subscribe(response =>
                               {
                                   result.Text = response.Locations[0].Name;
                               },
                               exn =>
                                   {
                                       result.Text = string.Format("FAILED! Message - '{0}'", exn.Message);
                                   });
        }
    }
}